package com.fbs.wowo.essay.service.imp;

import com.fbs.wowo.attest.entity.Attest;
import com.fbs.wowo.attest.mapper.AttestMapper;
import com.fbs.wowo.essay.entity.*;
import com.fbs.wowo.essay.mapper.EssayMapper;
import com.fbs.wowo.essay.service.EssayService;
import com.fbs.wowo.essay.vo.EssayQuery;
import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.forum.entity.Likes;
import com.fbs.wowo.forum.service.CommentsService;
import com.fbs.wowo.forum.service.LikesService;
import com.fbs.wowo.forum.vo.CommentsList;
import com.fbs.wowo.forum.vo.CommentsListQuery;
import com.fbs.wowo.manage.entity.Account;
import com.fbs.wowo.manage.entity.User;
import com.fbs.wowo.manage.mapper.AccountMapper;
import com.fbs.wowo.manage.mapper.UserMapper;
import com.fbs.wowo.userCollect.entity.UserCollect;
import com.fbs.wowo.userCollect.service.UserCollectService;
import com.fbs.wowo.userFollow.entity.UserFollow;
import com.fbs.wowo.userFollow.service.UserFollowService;
import com.fbs.wowo.util.common.ComUtils;
import com.fbs.wowo.util.common.Constants;
import com.fbs.wowo.util.eos.EOSService;
import com.fbs.wowo.util.eos.EOSServiceImp;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service("EssayService")
@Transactional
public class EssayServiceImp implements EssayService {

    @Resource
    private EssayMapper essayMapper;

    @Resource
    private EOSService eosService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AttestMapper attestMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private CommentsService commentsService;




    @Resource
    private LikesService likesService;

    @Resource
    private UserFollowService userFollowService;

    @Resource
    private UserCollectService userCollectService;


    //添加
    @Override
    public int insertSelective(Essay record) {
        Essay essay = essayMapper.findEssayByHash(record.getUserId(), record.getHashValue());
        if (essay!=null){
            throw new DataOverflowException(ErrorCode.ERR_ESSAY_ALREADY_ATTEST);
        }
        record.setId(ComUtils.getUUID());
        record.setCreateDate(new Date());
        record.setUpdateDate(new Date());
        //假如不是草稿
        if (record.getState()!=null && record.getState()==false){
            //登记
            checkIn(record);
            return essayMapper.insertSelective(record);
        }
        return essayMapper.insertSelective(record);
    }


    /**
     * 登记
     */
    public void checkIn(Essay record) {
        //生成上链数据
        Attest attest = new Attest();
        attest.setId(ComUtils.getUUID());           //主键id
        attest.setEssayId(record.getId());          //作品ID
        attest.setTitle(record.getTitle());         //作品标题
        attest.setUserId(record.getUserId());       //发布者
        attest.setCreateDate(new Date());           //上链时间
        attest.setEssayType(record.getType());      //文章类型
        attest.setHashValue(record.getHashValue()); //md5加密码
        //根据用户ID判断账户是否存在
        Account account = accountMapper.findByUserId(record.getUserId());
        if (account != null) {
            //假如是图文的时候调用eos
            if (record.getType() == 1) {
                EOSServiceImp.EosTransactionResponse eos = eosService.imagetextEvidence
                        (record.getUserId(), account.getPrivateKey(),"", record.getTitle(),
                                "", "", record.getHashValue(), "");
                if (eos!=null&&eos.getBlockNum()!=null){
                    attest.setBlockHeight(eos.getBlockNum());
                    attest.setRegisterId(eos.getTransactionId());
                    attest.setChainId(eos.getChainId());
                    attestMapper.insertSelective(attest);
                }else{
                    throw new DataOverflowException(ErrorCode.ERR_ATTEST_EOS_ERROR);
                }
            } else if (record.getType() == 2) {
                EOSServiceImp.EosTransactionResponse eos = eosService.audioEvidence
                        (record.getUserId(), account.getPrivateKey(),"", record.getTitle(),
                                "", "", record.getHashValue(), "");
                if (eos!=null&&eos.getTransactionId()!=null){
                    attest.setBlockHeight(eos.getBlockNum());
                    attest.setRegisterId(eos.getTransactionId());
                    attest.setChainId(eos.getChainId());
                    attestMapper.insertSelective(attest);
                }else{
                    throw new DataOverflowException(ErrorCode.ERR_ATTEST_EOS_ERROR);
                }
            } else {
                throw new DataOverflowException(ErrorCode.ERR_ATTEST_EOS_ERROR);
            }
        }else{
            throw new DataOverflowException(ErrorCode.ERR_RED_FROM_ACCOUNT_NULL);
        }
    }

    //推荐列表
    @Override
    public List<EssayListResponse> findRecommendList() {
        List<EssayListResponse> essayList = essayMapper.findRecommendList();
        for (EssayListResponse essay:essayList){
            Integer count = commentsService.count(essay.getEssayId(), essay.getType());
            essay.setCommentsNum(count);
        }
        return essayList;
    }





















    /**
     * 根据ID获取详情
     * @param id
     * @return
     */
    @Override
    public Essay selectByPrimaryKey(String id) {
        return essayMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(Essay record) {
        Essay ess = essayMapper.findEssayByHash(record.getUserId(), record.getHashValue());
        if (ess!=null){
            throw new DataOverflowException(ErrorCode.ERR_ESSAY_ALREADY_ATTEST);
        }
        record.setUpdateDate(new Date());
        if(record.getState()==false){
            Essay essay = essayMapper.selectByPrimaryKey(record.getId());
            if (essay!=null){
                //登记
                checkIn(essay);
                return essayMapper.updateByPrimaryKeySelective(record);
            }
            throw new DataOverflowException(ErrorCode.ERR_ESSAY_NULL);
        }
        return essayMapper.updateByPrimaryKeySelective(record);
    }

    //查询文章,音频列表
    @Override
    public List<EssayListResponse> queryEssayList(EssayQuery essayQuery) {
        List<EssayListResponse> e = essayMapper.queryEssayList(essayQuery);
        return e;
    }



    /**
     * 别人主页
     * @param userId
     * @return
     */
    @Override
    public UserHomeResponse findUserHomeByUserId(String loginUserId,String userId) {
        UserHomeResponse userHome = essayMapper.findUserHomeByUserId(userId);
        if (userHome!=null){
            UserFollow userFollow = userFollowService.selectByPrimaryKey(loginUserId, userId);
            if (userFollow!=null){      //关注状态
                userHome.setFollowState(true);
            }else{
                userHome.setFollowState(false);
            }
            EssayQuery voiceQuery = new EssayQuery();
            voiceQuery.setUserId(userId);
            voiceQuery.setType((byte) Constants.ENTITY_TYPE_VOICE);    //音频
            voiceQuery.setState((byte)0);   //不是草稿
            List<EssayListResponse> voiceList = essayMapper.queryEssayList(voiceQuery);
            userHome.setVoiceList(voiceList);   //音频列表
            userHome.setVoiceNum(voiceList.size()); //音频个数

            EssayQuery essayQuery = new EssayQuery();
            essayQuery.setUserId(userId);
            essayQuery.setType((byte) Constants.ENTITY_TYPE_ARTICLE);
            essayQuery.setState((byte)0);   //不是草稿
            List<EssayListResponse> essayList = essayMapper.queryEssayList(essayQuery);
            userHome.setEssayList(essayList);       //图文列表
            userHome.setEssayNum(essayList.size()); //图文个数
        }
        return userHome;
    }

    @Override
    public OneselfHomeResponse oneselfHomeByUserId(String userId) {
        return essayMapper.oneselfHomeByUserId(userId);
    }

    @Override
    public int deleteByPrimaryKey(String essayId,String userId) {
        Essay essay = essayMapper.selectByPrimaryKey(essayId);
        if (essay!=null){
            if (userId.equals(essay.getUserId())){
                //不是草稿上链
                if (essay.getState()==false){
                    Account account = accountMapper.findByUserId(essay.getUserId());
                    if (account!=null){
                        if (essay.getType()==1){
                            eosService.transcpyDeleteitem
                                    (essay.getUserId(),account.getPrivateKey(),essay.getHashValue(),"imagetext",
                                            "id为"+essay.getUserId()+"的用户删除了"+essay.getTitle());
                        }else if (essay.getType()==2){
                            eosService.transcpyDeleteitem
                                    (essay.getUserId(),account.getPrivateKey(),essay.getHashValue(),"audio",
                                            "id为"+essay.getUserId()+"的用户删除了"+essay.getTitle());
                        }
                    }
                }
                return essayMapper.deleteByPrimaryKey(essayId);
            }
            throw new DataOverflowException(ErrorCode.ERR_USER_NOT_EXIST);
        }
        throw new DataOverflowException(ErrorCode.ERR_NULL_DATA);

    }

    @Override
    public List<EssayListResponse> findEssayByClassifyId(String classifyId, int type) {
        return essayMapper.findEssayByClassifyId(classifyId,type);
    }


    /**
     * 查询图文音频详情
     * @param essayId   数据的id
     * @param uId   登录人的ID
     * @return
     */
    @Override
    public EssayInfoResponse findEssayInfo(String essayId,String uId) {
        //获取详情
        EssayInfoResponse essayInfo = essayMapper.findEssayInfo(essayId);
        //根据图文ID获取信息
        Essay essay = essayMapper.selectByPrimaryKey(essayId);
        if (essay!=null){
            //获取创建者的用户信息
            User user = userMapper.findByUserId(essay.getUserId());
            if (user!=null){
                //设置返回的作者名称及头像
                essayInfo.setUserName(user.getName());
                essayInfo.setUserPhoto(user.getPhoto());
            }else{
                throw new DataOverflowException(ErrorCode.ERR_USER_NOT_EXIST);
            }
            //文章
            if (essay.getType()==1){
                Integer likes = likesService.likes(essayId, Constants.ENTITY_TYPE_ARTICLE);
                if (likes==null){
                    essayInfo.setLikeNum(0);
                }else{
                    essayInfo.setLikeNum(likes);
                }
                //评论数
                essayInfo.setCommentNum(commentsService.count(essayId,Constants.ENTITY_TYPE_ARTICLE));
                //查询是否收藏
                UserCollect userCollect = userCollectService.selectByPrimaryKey(uId, essayId);
                if (userCollect==null){
                    essayInfo.setCollectState(false);
                }else{
                    essayInfo.setCollectState(true);
                }
                //评论列表
                CommentsListQuery com = new CommentsListQuery();
                com.setEntityId(essayId);
                com.setEntityType(Constants.ENTITY_TYPE_ARTICLE);
                List<CommentsList> list = commentsService.list(com);
                essayInfo.setComments(list);

                //点赞状态
                Likes likes1 = likesService.getLikes(essayId, Constants.ENTITY_TYPE_ARTICLE, uId);
                if (likes1!=null){
                    essayInfo.setLikeState(likes1.getStatus());
                }else{
                    essayInfo.setLikeState(0);
                }

                //音频
            }else if (essay.getType()==2){
                Integer likes = likesService.likes(essayId, Constants.ENTITY_TYPE_VOICE);
                if (likes==null){
                    essayInfo.setLikeNum(0);
                }else{
                    essayInfo.setLikeNum(likes);
                }
                //评论数
                essayInfo.setCommentNum(commentsService.count(essayId,Constants.ENTITY_TYPE_VOICE));
                //查询是否收藏
                UserCollect userCollect = userCollectService.selectByPrimaryKey(uId, essayId);
                if (userCollect==null){
                    essayInfo.setCollectState(false);
                }else{
                    essayInfo.setCollectState(true);
                }
                //评论列表
                CommentsListQuery com = new CommentsListQuery();
                com.setEntityId(essayId);
                com.setEntityType(Constants.ENTITY_TYPE_VOICE);
                List<CommentsList> list = commentsService.list(com);
                essayInfo.setComments(list);
                //点赞状态
                Likes likes1 = likesService.getLikes(essayId, Constants.ENTITY_TYPE_VOICE, uId);
                if (likes1!=null){
                    essayInfo.setLikeState(likes1.getStatus());
                }else{
                    essayInfo.setLikeState(0);
                }
            }
            essay.setPageView(essay.getPageView()+1);
            essayMapper.updateByPrimaryKeySelective(essay);
        }else{
            throw new DataOverflowException(ErrorCode.ERR_NULL_DATA);
        }
        return essayInfo;
    }

    /**
     * 查询用户作品个数
     * @param userId
     * @return
     */
    @Override
    public EssayNumResponse findMyEssayNum(String userId) {
        return essayMapper.findMyEssayNum(userId);
    }


    /**
     * 查询已确权的用户列表
     * @return
     */
    @Override
    public List<UserNameListResponse> confirmedUserList() {
        return essayMapper.confirmedUserList();
    }









}
